////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.monitor;

import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BaseActivity;
import cc.telecomdigital.tdstock.activity.groups.MonitorGroup;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;

/**
 * 
 * @author haibo
 * 
 *  for monitor item   -- stock diary
 *
 */
public class StockDiaryEditActivity extends BaseActivity
{

	protected static final String	TAG				= StockDiaryEditActivity.class
													.getSimpleName();

	private Button				_toolBtnReturn;

	private TextView			_top_bar_title;
	private Button				_diary_save;
	private DBHelper			_dbHelper;
	private DatePicker			_dp;
	private TextView			_tvOfShares;
	private TextView			_tvDiaryPrice;
	private EditText			_tvMemo;
	private boolean			_isCameFromPause	= false;
	private boolean			_isNewDiary		= false;
	private static Calendar		_calendar			= Calendar.getInstance();

	private String				_itemCode;								;
	private String				_date;
	private String				_ofShares;
	private String				_diaryPrice;
	private String				_memo;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		/*this.setContentView(R.layout.stock_diary);
		initToolButtons();
		resetMinHeightOnWorkCenter();
		 if(_dbHelper == null) {
			_dbHelper = new DBHelper(this);
		 }
		_top_bar_title = (TextView)findViewById(R.id.top_bar_title);
		_diary_add = (ViewGroup)findViewById(R.id.diary_add);*/

		this.setContentView(R.layout.stock_diary_edit);
		resetMinHeightOnWorkCenter();
		if (_dbHelper == null)
		{
			_dbHelper = new DBHelper(this);
		}
		_top_bar_title = (TextView) findViewById(R.id.top_bar_title);
		_diary_save = (Button) findViewById(R.id.toolbtn_save);
		_diary_save.setFocusable(true);
		_diary_save.setClickable(true);
		_diary_save.setOnClickListener(new SaveDiary(this));

		_dp = (DatePicker) findViewById(R.id.stock_diary_date);
		_tvOfShares = (TextView) findViewById(R.id.stock_diary_ofshares);
		_tvDiaryPrice = (TextView) findViewById(R.id.stock_diary_price);

		_tvMemo = (EditText) findViewById(R.id.stock_diary_memo);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog
						.d(TAG,
								"close current activity and forwarding to the previous");
				//MetalActivity.this.finish();

				//-----------decrease memory usage---------
				// finish();
				//-----------decrease memory usage---------

				/*Intent intent =new Intent(getApplicationContext(),StockDiaryActivity.class);
				//            	intent.putExtras(getIntent().getExtras());
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);*/

				Intent intent = new Intent(getApplicationContext(),
						StockDiaryActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				/*View view = MonitorGroup.group.getLocalActivityManager()
						.startActivity(
								StockDiaryActivity.class
										.getSimpleName(), intent)
						.getDecorView();
				MonitorGroup.group.setContentView(view); //modified by haibo, 2011-05-16
*/
				
				
				SwitchForwardActivity(StockDiaryActivity.class, intent);
			}

		});

	}

	@Override
	protected void onPause()
	{
		// TODO Auto-generated method stub
		super.onPause();
		//_isCameFromPause = true;
		_date = String.format("%s-%s-%s", _dp.getYear(), _dp.getMonth() + 1,
				_dp.getDayOfMonth());
		_ofShares = _tvOfShares.getText().toString();
		_diaryPrice = _tvDiaryPrice.getText().toString();
		_memo = _tvMemo.getText().toString();

	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		_tvMemo.setText("");
		_tvDiaryPrice.setText("");
		if (_dbHelper == null)
		{
			_dbHelper = new DBHelper(this);
		}
		super.onResume();
		updateLocalData();

		if (_isCameFromPause)
		{
			_isCameFromPause = false;
			if (_date != null && _date.length() >= 10)
			{
				_dp.init(Integer.parseInt(_date.substring(0, 4)), Integer
						.parseInt(_date.substring(5, 7)), Integer
						.parseInt(_date.substring(8, 10)), null);
			}

			_tvOfShares.setText(_ofShares == null ? "" : _ofShares);
			_tvDiaryPrice.setText(_diaryPrice == null ? "" : _diaryPrice);
			_tvMemo.setText(_memo == null ? "" : _memo);
		}
		else if (_isNewDiary)
		{
			_tvOfShares.setText("");
			_tvDiaryPrice.setText("");
			_tvMemo.setText("");
			_dp.init(_calendar.get(Calendar.YEAR), _calendar
					.get(Calendar.MONTH), _calendar.get(Calendar.DATE),
					null);
		}
		else
		{
			ITDLApplication app = (ITDLApplication) getApplicationContext();
			String date = app.getString(CommonDefn.STOCK_DIARY_EDITING_DATE);
			if (date != null)
				_dp.init(Integer.parseInt(date.substring(0, 4)), Integer
						.parseInt(date.substring(5, 7)) - 1, Integer
						.parseInt(date.substring(8, 10)), null);

			String ofShare = app
					.getString(CommonDefn.STOCK_DIARY_EDITING_OFSHARES);
			_tvOfShares.setText(ofShare == null ? "" : ofShare);

			String diaryPrice = app
					.getString(CommonDefn.STOCK_DIARY_EDITING_DIARY_PRICE);
			_tvDiaryPrice.setText(diaryPrice == null ? "" : diaryPrice);

			String memo = app.getString(CommonDefn.STOCK_DIARY_EDITING_MEMO);
			_tvMemo.setText(memo == null ? "" : memo);

		}

	}

	private void updateLocalData()
	{
		ITDLApplication app = (ITDLApplication) getApplicationContext();
		_top_bar_title.setText(app
				.getString(CommonDefn.STOCK_DIARY_EDITING_ITEMNAME));
		_itemCode = app.getString(CommonDefn.STOCK_DIARY_EDITING_ITEMCODE);
		_isNewDiary = app
				.getString(CommonDefn.STOCK_DIARY_EDITING_CURRENT_RECNO) == null
				|| Integer
						.parseInt(app
								.getString(CommonDefn.STOCK_DIARY_EDITING_CURRENT_RECNO)) < 1;

	}

	@Override
	protected void onDestroy()
	{
		// TODO Auto-generated method stub
		this._dbHelper.cleanup();
		super.onDestroy();
	}

	@Override
	protected void onRestart()
	{
		// TODO Auto-generated method stub
		if (_dbHelper == null)
		{
			_dbHelper = new DBHelper(this);
		}

		super.onRestart();
	}

	private class SaveDiary extends DefaultClickHandler
	{
		SaveDiary(Context context)
		{
			super(context);
		}

		@Override
		protected void onDefaultAction()
		{
			if (TextUtils.isDigitsOnly(_itemCode))
			{
				//it's stock; must fill the ofshare,  price;
				if (_tvOfShares.getText().toString().length() < 1
						|| _tvDiaryPrice.getText().toString().length() < 1)
				{
					new CustomizeDialog(StockDiaryEditActivity.this.getParent(), 
							getResources().getString(R.string.info),
							"需填寫股量和價格才能保存!",
							getResources().getString(R.string.ok))
					{
						@Override
						public void onClick(View v)
						{
							super.onClick(v);
							if (_tvOfShares.getText().toString().length() < 1)
							{
								_tvOfShares.requestFocus();
								return;
							}
							else
							{
								_tvDiaryPrice.requestFocus();   
							}
						}
					}.show();
					/*new AlertDialog.Builder(StockDiaryEditActivity.this
							.getParent())
							.setTitle(
									getResources().getString(
											R.string.info))
							.setMessage("需填寫股量和價格才能保存!")
							.setIcon(
									getResources()
											.getDrawable(
													R.drawable.help_menu_icon))
							.setPositiveButton(
									getResources().getString(
											R.string.ok),
									new DialogInterface.OnClickListener()
									{
										public void onClick(
												DialogInterface dialoginterface,
												int i)
										{
											if (_tvOfShares
													.getText()
													.toString()
													.length() < 1)
											{
												_tvOfShares
														.requestFocus();
												return;
											}
											else
											{
												_tvDiaryPrice
														.requestFocus();
											}

										}
									}).show();*/ //show failure message;

					return;
				}

			}
			else if (_tvDiaryPrice.getText().toString().length() < 1)
			{
				new CustomizeDialog(StockDiaryEditActivity.this.getParent(), 
						getResources().getString(R.string.info),
						"需填寫價格才能保存!",
						getResources().getString(R.string.ok))
				{
					@Override
					public void onClick(View v)
					{
						super.onClick(v);
						_tvDiaryPrice.requestFocus();
					}
				}.show();
				/*new AlertDialog.Builder(StockDiaryEditActivity.this
						.getParent()).setTitle(
						getResources().getString(R.string.info))
						.setMessage("需填寫價格才能保存!").setIcon(
								getResources().getDrawable(
										R.drawable.help_menu_icon))
						.setPositiveButton(
								getResources().getString(R.string.ok),
								new DialogInterface.OnClickListener()
								{
									public void onClick(
											DialogInterface dialoginterface,
											int i)
									{
										_tvDiaryPrice.requestFocus();
									}
								}).show();*/ //show failure message;
				return;
			}
			String recNo = "0";
			if (!_isNewDiary)
			{
				recNo = ((ITDLApplication) getApplicationContext())
						.getString(CommonDefn.STOCK_DIARY_EDITING_CURRENT_RECNO);
			}
			_date = String.format("%s-%02d-%02d", _dp.getYear(), _dp
					.getMonth() + 1, _dp.getDayOfMonth());
			_ofShares = _tvOfShares.getText().toString();
			_diaryPrice = _tvDiaryPrice.getText().toString();
			_memo = _tvMemo.getText().toString();

			if (_diaryPrice.equals(""))
			{
				_diaryPrice = "0";
			}
			if (_ofShares.equals(""))
			{
				_ofShares = "100";
			}

			long result = -1;
			try
			{
				TDStockLog.d(TAG, String.format("userid: %d, itemcode: %s",
						((ITDLApplication) getApplicationContext())
								.getUserId(-1), _itemCode));
				result = _dbHelper.insertOrUpdateStockDiary(Integer
						.parseInt(recNo),
						((ITDLApplication) getApplicationContext())
								.getUserId(-1), _itemCode, _date,
						Integer.parseInt(_ofShares), Double
								.parseDouble(_diaryPrice), _memo);
			}
			catch (NumberFormatException e)
			{
				// TODO Auto-generated catch block
				TDStockLog.d(TAG, e.getMessage() == null ? " update result: "
						+ result
						+ "-->unkonw exception happened, insert failure."
						: " update result: " + result + "->"
								+ e.getMessage());
			}
			catch (Exception e)
			{
				TDStockLog
						.d(
								TAG,
								e.getMessage() == null ? " update result: "
										+ result
										+ " -->unkonw exception happened, insert failure."
										: " update result: " + result
												+ "->"
												+ e.getMessage());
			}
			TDStockLog.d(TAG, " update diary result : " + result);
			_toolBtnReturn.performClick(); //return to the former activity;

		}

	}
	
	

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		//share the same tab with  more group,
		return MonitorGroup.GetActivityGroupHostControl() == null ?  MoreGroup.GetActivityGroupHostControl() : MonitorGroup.GetActivityGroupHostControl() ;
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(getApplicationContext(),
				StockDiaryActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		
		SwitchForwardActivity(StockDiaryActivity.class, intent);
	}
	
	
	
	

}
